# coding=utf8
#phon_corpus class to represent a corpus of child language productions
import phon_data
import phon_transcript
import phon_corpus
#import sys
#PATH = phon_corpus.__file__.split("objects/phon/phon_corpus.py")[0]
#if PATH == phon_corpus.__file__: #we are on windows
#    PATH = phon_corpus.__file__.split("objects\\phon\\phon_corpus.py")[0]
#sys.path.append(PATH + "\\util")
import utility
import corpus_reader
class phon_corpus(object):
    """A representation of a corpus of spoken child language.
    More formally, a phon_corpus contains both a list of phon_transcripts
    and also a flat list of all phon_data tokens"""
    def __init__(self, url_corpus_name):
        self.title = url_corpus_name
        self.transcripts = corpus_reader.read_url_corpus(url_corpus_name)
        self.tokens = []
        for t in self.transcripts:
            for token in t.data:
                self.tokens.append(token)
        self.child_symbols = self.get_symbols()[0]
        self.adult_symbols = self.get_symbols()[1]
        self.labelled_sequences = [token.align() for token in self.tokens]
        
    def add_childes_transcripts(self, url):
        """Takes a url from the CHILDES database as input
        and adds all transcripts of the child data
        to the corpus"""
        t = utility.url_to_phon_transcripts(url)
        for transcript in t:
            self.transcripts.append(transcript)
            for token in transcript.data:
                self.tokens.append(token)
                
    def add_childes_transcript(self, url):
        """Takes a url from the CHILDES database as input
        and adds that single transcript to the corpus"""
        t = utility.url_to_phon_transcript(url)
        self.transcripts.append(t)
        for token in t:
            self.tokens.append(t)
            
    def get_symbols(self):
        """
        Finds all the unique IPA values from the child form
        and adult form, returning them as a 2-tuple.

        Args:
            None
        Returns:
            A tuple of two list, where the first is the unique child symbols
            and the second is all the unique adult symbols.
        
        """
        child_symbols = []
        adult_symbols = []
        for token in self.tokens:
            child_symbols += [symbol for symbol in token.child_symbols]
            adult_symbols += [symbol for symbol in token.adult_symbols]
        return(list(set(child_symbols)), list(set(adult_symbols)))

    def segment_align(self, childSegment, adultSegment):
        """
        Finds all phon_data tokens where the tuple
        (childSegment, adultSegment) exists in the aligned form.

        Args:
            childSegment: the segment of the child form
            adultSegment: the segment of the adult form
        Returns:
            a list of tuples for pairs of (childSegment, adultSegment)
            
        """
        CHILD = 0
        ADULT = 1
        instances = []
        for p in self.tokens:
            form = p.align()
            for pair in form:
                if pair[CHILD] == childSegment and pair[ADULT] == adultSegment:
                    instances.append(p)
        return instances
                    

    def write_crfsuite_tokens(self, mindex, maxdex, path = "", reverse = False):
        """
        Writes phon_data tokens from self.tokens to a text file
        formatted to the CRFSuite form, from self.tokens[mindex:maxdex].
        Path can be specified, otherwise the text file is written to
        the same directory as phon_corpus.py.

        Args:
            mindex: min integer index of self.tokens
            maxdex: max integer index of self.tokens
            path: string for absolute name of CRFSuite training file
            reverse: boolean, if true adult forms are SR and child forms URs
        Returns:
            None (writes a file at specified path)

        """
        crfsuite_file = open(path + "\\" "crf_" + self.tokens[0].name + "_" + str(mindex) + "_" + str(maxdex) + ".txt", 'w')
        for token in self.tokens[mindex:maxdex]:
            print>>crfsuite_file, token.crfsuite_form(reverse).encode("utf-8")
        crfsuite_file.close()
    
    def print_adult_symbols(self):
        """
        Prints out the list of unique adult symbols

        Args:
            None
        Returns:
            None (prints a string)

        """
        printout = "["
        for index in range(0, len(self.adult_symbols)):
            if index < (len(self.adult_symbols) - 1):
                printout += self.adult_symbols[index] + ", "
            else:
                printout += self.adult_symbols[index]
        printout += "]"
        print printout
        
    def print_child_symbols(self):
        """
        Prints out the list of unique child symbols

        Args:
            None
        Returns:
            None (prints a string)

        """
        printout = "["
        for index in range(0, len(self.child_symbols)):
            if index < (len(self.child_symbols) - 1):
                printout += self.child_symbols[index] + ", "
            else:
                printout += self.child_symbols[index]
        printout += "]"
        print printout
        
            
            
    
    
        
            
        
        
    
